﻿#region Copyright information
// 
// Copyright © 2005-2013 Yongkee Cho. All rights reserved.
// 
// This code is a part of the Biological Object Library and governed under the terms of the
// GNU Lesser General  Public License (LGPL) version 2.1 which accompanies this distribution.
// For more information on the LGPL, please visit http://bol.codeplex.com/license.
// 
// - Filename: OneWayANOVATest.cs
// - Author: Yongkee Cho
// - Email: yongkeecho@gmail.com
// - Date Created: 2012-09-06 11:39 AM
// - Last Modified: 2013-01-25 3:59 PM
// 
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using BOL.Maths.Distributions;

namespace BOL.Maths.Statistics.HypothesisTest
{
    public sealed class OneWayANOVATest<TKey> : TestBase
    {
        #region Private variables

        private readonly double[][] _sample;
        private readonly double[] _means;
        private readonly int _db;
        private readonly int _dw;

        #endregion

        #region Constructors

        public OneWayANOVATest(double alpha, IEnumerable<IGrouping<TKey, double>> sample)
            : base(TestType.Upper, alpha, 0)
        {
            if (sample == null)
                throw new ArgumentNullException("sample");

            _sample = sample.Select(l => l.ToArray()).ToArray();
            _means = _sample.Select(s => s.Average()).ToArray();
            _db = _sample.Length - 1;
            _dw = _sample.Sum(s => s.Length - 1);

            Distribution = new FDistribution(_db, _dw);
        }

        public OneWayANOVATest(IEnumerable<IGrouping<TKey, double>> sample)
            : this(0.05, sample) { }

        #endregion

        #region Protected methods

        protected override double PointEstimate()
        {
            var overallMean = _means.Average();
            var ssb = _sample.Zip(_means, (s, m) => s.Length * Math.Pow(m - overallMean, 2)).Sum();
            return ssb / _db;
        }

        protected override double PointEstimateStandardError()
        {
            var ssw = _sample.Zip(_means, (s, m) => s.Sum(x => Math.Pow(x - m, 2))).Sum();
            return ssw / _dw;
        }

        #endregion

        #region Object overriden

        public override string ToString()
        {
            return String.Format("One-way ANOVA (F-Statistic = {0:G3}, p-value = {1:G3}): {2}", TestStatistic, PValue, (IsSignificant) ? "Reject H0" : "Accept H0");
        }

        #endregion
    }
}
